package com.djw.controller;

import com.djw.model.User;
import com.djw.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.UUID;

@RestController
@RequestMapping(value = "User")
@Api(value = "用户控制层",description = "包含对用户的各种操作")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping(value = "getUser")
    @ApiOperation(value = "得到用户的详细信息",notes = "根据用户id查询用户的详细信息")
    public User getUser(HttpServletRequest request, String id){
        User user = userService.getUser(id);
        request.setAttribute("user",user);
        return user;
    }

    @PostMapping(value = "register")
    @ApiOperation(value = "注册",notes = "用户的注册")
    public String register(HttpServletRequest request,String userName,String email,String phone,String sex,String password){
        User user = new User();
        user.setId(UUID.randomUUID().toString());
        user.setName(userName);
        user.setEmail(email);
        user.setPhone(phone);
        user.setPassword(password);
        user.setSex(sex);
        user.setRegisterTime(new Date());
        if (userService.insert(user) == 1){
            request.setAttribute("user",user);
        }
        return "index";
    }

    @PostMapping(value = "login")
    @ApiOperation(value = "登录",notes = "用户登录接口")
    public String login(HttpServletRequest request,String userName,String password){
       User user = userService.selectUser(userName);
       if (user != null){
           if (user.getPassword().equals(password)){
               return "success";
           }else {
               request.setAttribute("error","密码错误！");
               return "error";
           }
       }else {
           request.setAttribute("error","用户名不存在！");
           return "error";
       }
    }
}
